use apperror::{AnyError, AnyResult};
use chrono::Local;
use command::greet;
use command::predict::seir_predict;
use command::user::{
    async_upload, download, get_file_info, get_files_command, get_object_list, get_user_state,
    login, ratatui, register_handler, test_err, upload_token,
};
use func::{on_window_event, setup};
use tauri::Manager;
mod app_error;
mod command;
mod extensions_trait;
mod func;
mod payload;
mod state_manage;
mod subscriber;
// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() -> AnyResult<()> {
    let mut builder = tauri::Builder::default()
        .plugin(tauri_plugin_shell::init())
        .plugin(tauri_plugin_process::init())
        .plugin(tauri_plugin_dialog::init());
    #[cfg(desktop)]
    {
        builder = builder.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
            let _ = app
                .get_webview_window("main")
                .expect("no main window")
                .set_focus();
        }));
    }
    builder
        .plugin(tauri_plugin_notification::init())
        .setup(|app| {
            //连接后续换为云数据库
            setup(app.handle());
            Ok(())
        })
        .on_window_event(|window, event| {
            on_window_event(window, event);
        })
        .plugin(
            tauri_plugin_log::Builder::new()
                .level(log::LevelFilter::Info)
                .target(tauri_plugin_log::Target::new(
                    tauri_plugin_log::TargetKind::LogDir {
                        file_name: Some(format!("{}", Local::now().format("%Y-%m-%d"))),
                    },
                ))
                .build(),
        )
        .plugin(tauri_plugin_fs::init())
        .manage(state_manage::UserState::init())
        .manage(state_manage::ChildProcessRatatuiState::init())
        .plugin(tauri_plugin_store::Builder::default().build())
        .plugin(tauri_plugin_upload::init())
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_fs::init())
        .invoke_handler(tauri::generate_handler![
            greet,
            login,
            register_handler,
            upload_token,
            get_object_list,
            test_err,
            download,
            async_upload,
            get_user_state,
            get_file_info,
            get_files_command,
            seir_predict,
            ratatui
        ])
        .run(tauri::generate_context!())
        .map_err(|e| AnyError::builder().context("Error", e).build())?;
    Ok(())
}
